import { openDB } from 'idb'
import type { IDBPDatabase } from 'idb'

import { useRef, useEffect } from 'react'
import { Message } from '@arco-design/web-react'
import { DBNAME, StoreNames } from '@/common'

/**
 * useIndexDbHooks：数据控制器
 */
export const useIndexDbHooks = () => {
  const dataBase = useRef<IDBPDatabase>()

  const initDb = async () => {
    if (dataBase.current) return
    const db = await openDB(DBNAME, 1, {
      upgrade(db) {
        db.createObjectStore(StoreNames.MODELSTORE, {
          keyPath: 'modelName'
        })
      }
    })
    dataBase.current = db
    // initTable('modelStore')
  }

  const addModel = async (storeName: string, data: any) => {
    const res = await dataBase.current?.add(storeName, data).catch((err) => {
      console.log('err:', err)
      updateModel(storeName, data)
    })
    if (res) {
      Message.success('添加成功')
    }
  }

  const updateModel = async (storeName: string, data: any) => {
    const res = await dataBase.current?.put(storeName, data).catch((err) => {
      console.log('err:', err)
    })
    if (res) {
      Message.success('更新成功')
    }
  }

  const getModelDataByKey = async (storeName: string, modelName: string) => {
    const res = await dataBase.current?.get(storeName, modelName).catch((err) => {
      console.log('err:', err)
    })
    return res
  }

  const getModelAllData = async <T>(storeName: string): Promise<T[]> => {
    if (!dataBase.current) {
      return new Promise((resolve) => {
        const timer = setTimeout(() => {
          clearTimeout(timer)
          resolve(getModelAllData(storeName))
        }, 100)
      })
    }

    const res = await dataBase.current?.getAll(storeName).catch((err) => {
      console.log('err:', err)
      return []
    })
    return res || []
  }

  useEffect(() => {
    initDb()
    return () => {
      // dataBase.current?.close()
    }
  }, [])

  return { dataBase, addModel, getModelDataByKey, getModelAllData }
}
